﻿#include "config.h"
#include <QFile>
#include <QString>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonValue>
#include <QDir>
#include <QCoreApplication>
#include <QTextStream>
#include <QStringLiteral>

Config::Config()
{
    QString fileName = QCoreApplication::applicationDirPath()+"/config.json";
    qDebug()<<fileName;
    file = new QFile(fileName);
    file->open(QIODevice::ReadWrite);
    QTextStream inStream(file);

    QString allData = inStream.readAll();
    qDebug()<<allData;

    QJsonParseError jsonError;
    document=QJsonDocument::fromJson(allData.toLocal8Bit(), &jsonError);
    if(jsonError.error != QJsonParseError::NoError)
    {
        QJsonObject jsonObject;
        qDebug() << "配置加载错误，已新建默认配置！" << jsonError.errorString();
        file->resize(0);
        jsonObject.insert(QString("workSteps"), 50);
        jsonObject.insert(QString("breakSteps"), 10);
        jsonObject.insert(QString("postoffMax"), 2);
        document.setObject(jsonObject);
        file->write(document.toJson());
    }
    else
    {
        printConfig();
    }
    file->close();

}

Config::~Config()
{
    delete file;
}

int Config::getConfig(QString key)
{
    QJsonObject jsonObject=document.object();
    if(jsonObject.contains(key))
    {
         int value = jsonObject.value(key).toInt();
         return value;
    }
    else
    {
      return -1;
    }
}

void Config::setConfig(QString key, const QJsonValue &value)
{
    file->open(QIODevice::WriteOnly);
    QJsonObject jsonObject=document.object();
    if(jsonObject.contains(key))
    {
        jsonObject[key]=value;
    }
    else
    {
        jsonObject.insert(key, value);
    }
    file->resize(0);
    document.setObject(jsonObject);
    file->write(document.toJson());
    file->close();
}

void Config::printConfig()
{
    QJsonObject jsonObject = document.object();
    qDebug()<<jsonObject["workSteps"];
    qDebug()<<jsonObject["breakSteps"];
    qDebug()<<jsonObject["postoffMax"];
}
